home *** CD-ROM | disk | FTP | other *** search
- Path: user2.mnsinc.com!huang
- From: huang@mnsinc.com (Szu-Wen Huang)
- Newsgroups: comp.lang.c
- Subject: Re: Can anyone help a newbie out ?
- Date: 12 Apr 1996 14:57:47 GMT
- Organization: Monumental Network Systems
- Message-ID: <4klr1b$29d@news1.mnsinc.com>
- References: <4kkf3r$5b0@darwin.nbnet.nb.ca>
- NNTP-Posting-Host: user.mnsinc.com
- X-Newsreader: TIN [version 1.2 PL2]
-
- Jeff (lewwid@brunswickmicro.nb.ca) wrote:
-
- : Problem:Write a function that accepts two strings. Count the number
- : of characters in each string, and return the pointer to the longer
- : string.
-
- Rule #1: learn thy standard libraries and thy miseries will end. Look
- up on 'strlen()'. :)
-
- [snip]
- : /* Checksize .. checks to see which array of char is longer, and
- : returns the longest of the 2 */
- : char checksize(char x[], char y[])
- : {
- : int count, int total = 0, int total1 = 0;
-
- : while (*x != NULL)
- : total += 1
-
- 1. Won't compile because you are missing a semicolon
- 2. Since x is a char[], *x is a char. NULL is a pointer. You should
- use a 0, or better yet, '\0' because you're looking for the null
- terminator of the ASCIIZ string.
- 3. Note that x never changes. You're always checking the first character
- of x[].
- *. (stylistic) "+= 1" is probably easier to read if written as "++".
- *. A good programmer will check if x is NULL first.
-
- Now, putting that all together,
-
- char *s;
-
- if (x != NULL) {
- s = x;
- while (*s != '\0') {
- total++;
- s++;
- }
- }
-
- (Note that you can also write the loop as:)
-
- while (*s++ != '\0')
- total++;
-
- (or better yet)
-
- total = strlen(x);
-
- : while (*y != NULL)
- : total1 += 1
-
- : if (total < total2)
- : return *y;
- : if (total > total2)
- : return *x;
-
- *y and *x are characters. Your declaration said to return characters,
- but your specification said to return a pointer to the characters. You'll
- want to change it to:
-
- char *checksize(char x[], char y[])
-
- and return x or y. Hth.
-
- :}
-
-